import { Text, View, StyleSheet, TouchableWithoutFeedback, Image, SafeAreaView, ScrollView, ImageBackground, useWindowDimensions, StatusBar } from 'react-native'
import React, { Component, useState } from 'react'
import { connect } from 'react-redux'
import { } from "../../redux/features/dappSlice"
import { pTx } from "../../utils/dimensions"
import { popularDapp, BSCDapp, ETHDapp, MACTDapp } from "../../utils/browserDapp"
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"




const TabViewExample = ({ navigation }) => {
    const layout = useWindowDimensions();
    const [index, setIndex] = useState(0);
    const [routes] = useState([
        { key: 'BSC', title: 'BSC' },
        { key: 'ETH', title: 'ETH' },
        { key: 'MACT', title: 'Polygon' },
    ]);

    renderTabBar = (props) => {
        return (
            <View style={{}}>
                <TabBar
                    {...props}
                    style={{
                        backgroundColor: '#fff',
                        elevation: 0
                    }}
                    activeColor={'#0A0C14'}
                    inactiveColor={'#0A0C14'}
                    indicatorStyle={{
                        backgroundColor: '#06C161',
                        elevation: 0,
                    }}
                    renderLabel={({ route, focused, color }) => (
                        <Text
                            style={{
                                color,
                                fontSize: pTx(16)
                            }}>
                            {route.title}
                        </Text>
                    )}
                />
            </View>
        );
    }
    const Route = (row) => {
        const realm = useRealm();
        const browserSearchLogs = useQuery(schemaName.BrowserSearchLogs).sorted('time', true)
        const onToSubmit = (item, id) => {
            navigation.navigate('web3View', { url: item.url, title: item.title })
            const list = browserSearchLogs.filtered(`url == '${item.url}'`)
            if (list.length == 0) {
                realm.write(() => {
                    realm.create(schemaName.BrowserSearchLogs, {
                        _id: new Realm.BSON.UUID(),
                        url: item.url,
                        icon: item.icon,
                        title: item.title,
                        time: Date.parse(new Date()) / 1000,
                    }, true)
                })
            } else {
                realm.write(() => {
                    realm.create(schemaName.BrowserSearchLogs, {
                        ...list[0],
                        icon: item.icon,
                        title: item.title,
                        time: Date.parse(new Date()) / 1000,
                    }, true)
                })
            }
        }
        return (
            <>
                {
                    { BSC: BSCDapp, ETH: ETHDapp, MACT: MACTDapp }[row.route.key].map((item, index) => {
                        return (
                            <TouchableWithoutFeedback onPress={() => onToSubmit(item, item.id)} key={index}>
                                <View style={[styles.routeCell]} key={index}>
                                    <Image style={styles.cellImage} source={{ uri: item.icon }}></Image>
                                    <View style={styles.routeCellInfo}>
                                        <Text style={styles.routeCellName} ellipsizeMode={'tail'} numberOfLines={2}>{item.title}</Text>
                                        <Text style={styles.routeCellText} ellipsizeMode={'tail'} numberOfLines={2}>{item.describe}</Text>
                                    </View>
                                </View>
                            </TouchableWithoutFeedback>
                        )
                    })
                }
                <Text style={styles.more} >没有更多了</Text>
            </>
        )
    }


    const renderScene = SceneMap({
        BSC: Route,
        ETH: Route,
        MACT: Route,
    });

    return (
        <View style={[{ minHeight: pTx(90 + ({ BSC: BSCDapp, ETH: ETHDapp, MACT: MACTDapp }[routes[index].key].length * 70)) }]}>
            <TabView
                renderTabBar={renderTabBar}
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
                initialLayout={{ width: layout.width }}
            />
        </View>
    );
}

const Dapp = (props) => {
    const realm = useRealm();
    const browserSearchLogs = useQuery(schemaName.BrowserSearchLogs).sorted('time', true)
    const onToSubmit = (item, id) => {
        props.navigation.navigate('web3View', { url: item.url, title: item.title })
        const list = browserSearchLogs.filtered(`url == '${item.url}'`)
        if (list.length == 0) {
            realm.write(() => {
                realm.create(schemaName.BrowserSearchLogs, {
                    _id: new Realm.BSON.UUID(),
                    url: item.url,
                    icon: item.icon,
                    title: item.title,
                    time: Date.parse(new Date()) / 1000,
                }, true)
            })
        } else {
            realm.write(() => {
                realm.create(schemaName.BrowserSearchLogs, {
                    ...list[0],
                    icon: item.icon,
                    title: item.title,
                    time: Date.parse(new Date()) / 1000,
                }, true)
            })
        }
    }
    return (
        <SafeAreaView style={styles.container}>
            <StatusBar backgroundColor="rgba(237, 237, 237, 1)" barStyle={"dark-content"} />
            <ScrollView style={styles.scrollView} >
                <View style={styles.search}>
                    <Text style={styles.searchLabel} onPress={() => props.navigation.navigate('search')}>搜索DApp或输入链接进入玩耍</Text>
                    <Image style={styles.searchIcon} source={require('../../assets/image/icon2.png')}></Image>
                </View>
                <View style={styles.page}>
                    <ImageBackground source={require('../../assets/image/banner.png')} resizeMode="cover" style={styles.banner}>
                        <View style={styles.bannerInfo}>
                            <Text style={styles.bannerTitle}>区块链世界Web3入口</Text>
                            <Text style={styles.bannerText}>为全球用户进入Web3世界降低门槛及便捷</Text>
                        </View>
                    </ImageBackground>
                    <View style={styles.myDapp}>
                        <View style={styles.titleBox}>
                            <Text style={styles.title}>我的DApps</Text>
                            <Text style={styles.more} onPress={() => props.navigation.navigate('myDapp')}>查看更多 ></Text>
                        </View>
                        <ScrollView horizontal={true}>
                            <View style={styles.row}>
                                <TouchableWithoutFeedback onPress={() => props.navigation.navigate('search')}>
                                    <View style={styles.cell}>
                                        <Image style={styles.cellImage} source={require('../../assets/image/DAppBrowser.png')}></Image>
                                        <Text style={styles.cellName} ellipsizeMode={'tail'} numberOfLines={2}>Dapp浏览器</Text>
                                    </View >
                                </TouchableWithoutFeedback>
                                {browserSearchLogs.slice(0, 10).map((item, index) => {
                                    return (
                                        <TouchableWithoutFeedback onPress={() => onToSubmit(item, item._id)} key={index}>
                                            <View style={styles.cell}>

                                                {
                                                    item.icon ?
                                                        <Image style={styles.cellImage} source={{ uri: item.icon }}></Image>
                                                        :
                                                        <Image resizeMode="contain" style={styles.cellImage} source={require('../../assets/image/icon40.png')}></Image>

                                                }
                                                <Text style={styles.cellName} ellipsizeMode={'tail'} numberOfLines={2}>{item.title || '网页无法打开'}</Text>
                                            </View >
                                        </TouchableWithoutFeedback>
                                    )
                                })}
                            </View>
                        </ScrollView>
                    </View>
                    <View style={styles.popular}>
                        <View style={styles.titleBox}>
                            <Text style={styles.title}>热门DApp</Text>
                        </View>
                        <View style={[styles.row, styles.row2]}>
                            {popularDapp.map((item, index) => {
                                return (
                                    <TouchableWithoutFeedback onPress={() => onToSubmit(item, index)} key={index}>
                                        <View style={[styles.cell, { marginRight: 0, marginBottom: pTx(13) }]}>
                                            <Image style={styles.cellImage} source={{ uri: item.icon }}></Image>
                                            <Text style={styles.cellName} ellipsizeMode={'tail'} numberOfLines={2}>{item.title}</Text>
                                        </View >
                                    </TouchableWithoutFeedback>
                                )
                            })}
                        </View>
                    </View>
                    <TabViewExample {...props} />
                </View>
            </ScrollView>
        </SafeAreaView>
    )
}

const mapStateToProps = (state) => state.dapp
const mapDispatchToProps = {

}
export default connect(mapStateToProps, mapDispatchToProps)(Dapp)

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    search: {
        paddingVertical: pTx(10),
        paddingHorizontal: pTx(15),
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        backgroundColor: "rgba(237, 237, 237, 1)"
    },
    searchLabel: {
        flex: 1,
        height: pTx(32),
        lineHeight: pTx(32),
        paddingHorizontal: pTx(15),
        backgroundColor: "#fff",
        color: "rgba(175, 181, 189, 1)",
        borderRadius: pTx(6),
    },
    searchIcon: {
        marginLeft: pTx(12),
        width: pTx(18),
        height: pTx(18),
    },
    page: {
        padding: pTx(15),
        backgroundColor: "#fff",
    },
    banner: {
        height: pTx(105),
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "flex-end"
    },
    bannerInfo: {
        paddingRight: pTx(40),
    },
    bannerTitle: {
        fontSize: pTx(12),
        color: "#fff",
        textAlign: "center"
    },
    bannerText: {
        marginTop: pTx(3),
        fontSize: pTx(6),
        color: "#fff",
        textAlign: "center"
    },
    myDapp: {
        marginTop: pTx(10),
    },
    titleBox: {
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "space-between"
    },
    title: {
        fontSize: pTx(16),
        color: "rgba(10, 12, 20, 1)"
    },
    more: {
        fontSize: pTx(14),
        color: "rgba(175, 181, 189, 1)"
    },
    row: {
        flexDirection: 'row',
        paddingVertical: pTx(15),
    },
    row2: {
        flexWrap: "wrap",
        justifyContent: "space-between"
    },
    cell: {
        width: pTx(65),
        alignItems: "center"
    },
    cellImage: {
        width: pTx(45),
        height: pTx(45),
        borderColor: "rgba(175, 181, 189, 0.2)",
        borderWidth: 1,
        borderRadius: pTx(12),
    },
    cellName: {
        marginTop: pTx(5),
        fontSize: pTx(12),
        textAlign: "center",
        color: "rgba(10, 12, 20, 1)",
    },
    routeCell: {
        marginTop: pTx(10),
        paddingBottom: pTx(10),
        flexDirection: 'row',
        alignItems: "center",
        borderColor: "rgba(175, 181, 189, 0.15)",
        borderBottomWidth: 1
    },
    routeCellInfo: {
        marginLeft: pTx(12),
    },
    routeCellName: {
        fontSize: pTx(16),
        color: "rgba(10, 12, 20, 1)"
    },
    routeCellText: {
        marginTop: pTx(3),
        fontSize: pTx(13),
        color: "rgba(175, 181, 189, 1)"
    },
    more: {
        marginTop: pTx(10),
        textAlign: "center"
    }
})